package com.chat.transmission.service.impl;

import com.chat.common.common.constant.RedisKeyConstant;
import com.chat.common.dto.MessageDTO;
import com.chat.common.entity.HistoryMessage;
import com.chat.transmission.event.event.UserSendMsgEvent;
import com.chat.transmission.event.source.SendMsgEventSource;
import com.chat.transmission.service.RabbitMqService;
import com.google.gson.Gson;
import jakarta.annotation.Resource;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.context.event.EventListener;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author wei kunJie
 * @date 2024/3/22 20:34:36
 */
@Service
public class RabbitMqServiceImpl implements RabbitMqService {
    //手动发消息
    @Resource
    private StreamBridge streamBridge;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Resource
    private Gson gson;

    @Override
    public boolean sendMsg(HistoryMessage historyMessage){
        // 构建消息对象
        Message<HistoryMessage> message = MessageBuilder.withPayload(historyMessage).build();
        return streamBridge.send("historyMessage-out-0", message);
    }

    /**
     * 监听用户发送消息事件
     * @param userSendMsgEvent
     */
    @Override
    @EventListener
    @Async("taskExecutor")
    public void onUserSendMsgEvent(UserSendMsgEvent userSendMsgEvent) {
        SendMsgEventSource sendMsgEventSource = (SendMsgEventSource) userSendMsgEvent.getSource();
        //获得用户发送的消息
        MessageDTO messageDTO = sendMsgEventSource.getMessageDTO();
        //获取发送消息的用户id
        Long userId = (Long) redisTemplate.opsForValue().get(RedisKeyConstant.TOKEN_USER + messageDTO.getUserToken());
        //获取发送消息的用户account
        String account = (String) redisTemplate.opsForValue().get(RedisKeyConstant.TOKEN_ACCOUNT + messageDTO.getUserToken());
        //构建数据库保存对象
        HistoryMessage historyMessage=new HistoryMessage();
        historyMessage.setUserId(userId);
        historyMessage.setUserAccount(account);
        historyMessage.setTime(LocalDateTime.parse(messageDTO.getTime()));
        historyMessage.setUserAvatar(messageDTO.getUserAvatar());
        historyMessage.setUserName(messageDTO.getUserName());
        historyMessage.setIsGroup(messageDTO.getIsGroup());
        historyMessage.setToUserAccount(messageDTO.getToUserAccount());
        historyMessage.setContent(gson.toJson(messageDTO.getContentItemList()));//将消息内容以json的方式保存

        sendMsg(historyMessage);//向消息队列发送消息
    }


}
